/*
 * Copyright 2011 Stefan Ferstl
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.debmavenplugin.archiver.ar.deb;

import java.io.File;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Set;
import java.util.TreeSet;

import com.google.code.debmavenplugin.archiver.ArchiveMetaData;
import com.google.code.debmavenplugin.archiver.ArchiveMetaData.ArchiveEntryMetaData;
import com.google.code.debmavenplugin.archiver.ar.ArArchiveCollectingFileFilter;
import com.google.code.debmavenplugin.archiver.ar.FileArArchiveEntry;


/**
 * File filter that collects the content of a Debian package.
 */
public class DebianPackageCollectingFileFilter extends ArArchiveCollectingFileFilter {

  private Set<FileArArchiveEntry> archiveContent;

  /**
   * Constructor.
   *
   * @param metaData Metadata of the Debian package-
   */
  public DebianPackageCollectingFileFilter(ArchiveMetaData metaData) {
    super(metaData, false);
    this.archiveContent = new TreeSet<FileArArchiveEntry>(new Comparator<FileArArchiveEntry>() {
      // We need to have the archive entries in a specific order..
      @Override
      public int compare(FileArArchiveEntry o1, FileArArchiveEntry o2) {
        if(DebPackageConstants.DEB_BINARY_FILE.equals(o1.getName())) {
          return -1;
        } else if (DebPackageConstants.CONTROL_ARCHIVE.equals(o1.getName())) {
          return 0;
        } else if (DebPackageConstants.DATA_ARCHIVE.equals(o1.getName())) {
          return 1;
        } else {
          throw new IllegalArgumentException("File '" + o1 + "' must not be part of a debian package.");
        }
      }
    });
  }

  /**
   * {@inheritDoc}
   */
  @Override
  protected void collectFile(File file) {
    String archivePath = createPath(getMetaData().getBaseDirectory(), file);
    ArchiveEntryMetaData entryMetaData = getMetaData().getEntryMetaData(file);
    int fileMode = entryMetaData.getFileMode() != null ? entryMetaData.getFileMode() : 0;
    FileArArchiveEntry archiveEntry = new FileArArchiveEntry(file, archivePath, 0, 0, fileMode, new Date().getTime() / 1000);
    this.archiveContent.add(archiveEntry);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public Set<FileArArchiveEntry> getCollectedFiles() {
    return Collections.unmodifiableSet(this.archiveContent);
  }
}
